package com.xxxx.crm.service;

import java.util.Calendar;
import java.util.Date;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.xxxx.crm.base.BaseService;
import com.xxxx.crm.dao.ClockMapper;
import com.xxxx.crm.dao.UserMapper;
import com.xxxx.crm.utils.AssertUtil;
import com.xxxx.crm.vo.Clock;
import com.xxxx.crm.vo.User;


@Service
public class ClockService extends BaseService<Clock, Integer> {

    @Resource
    private ClockMapper clockMapper;

    @Resource
    private UserMapper userMapper;



    /**
     * 查询用户当天打卡记录
     * @param userId 用户ID
     * @param date
     * @return Clock
     */
    public Clock queryTodayClock(Integer userId, Date date) {
        AssertUtil.isTrue(userId == null, "用户ID不能为空");
        return clockMapper.queryTodayClockByUserId(userId, new Date());
    }

    /**
     * 根据用户名进行上班打卡
     */
    public Integer clockInWithUsername(String username, String clockInTime) {
        // 根据用户名查询用户ID
        User user = userMapper.queryUserByName(username);
        if (user == null) {
            throw new RuntimeException("用户不存在！");
        }

        // 将时间戳字符串转换为Date对象
        Date date;
        try {
            long timestamp = Long.parseLong(clockInTime);
            date = new Date(timestamp);
        } catch (NumberFormatException e) {
            throw new RuntimeException("无效的时间格式");
        }

        // 查询当天的打卡记录
        Clock todayClock = queryTodayClock(user.getId(), new Date());
        if(todayClock.getClockInTime() != null){
            return 1;
        }
        
        // 判断打卡时间是否超过9点
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        
        // 创建打卡记录
        Clock clock = new Clock();
        clock.setUserId(user.getId());
        clock.setClockInTime(date);
        clock.setCreateTime(new Date());
        
        // 设置打卡状态：9点后打卡为迟到
        if (hour >= 9) {
            clock.setClockInStatus((byte) 1); // 1表示迟到
        } else {
            clock.setClockInStatus((byte) 0); // 0表示正常
        }
        
        // 保存打卡记录
        int rows = clockMapper.insert(clock);

        return rows;
    }

    /**
     * 根据用户名进行下班打卡
     */
    public Integer clockOutWithUsername(String username, String clockTime) {
        // 根据用户名查询用户ID
        User user = userMapper.queryUserByName(username);
        if (user == null) {
            throw new RuntimeException("用户不存在！");
        }

        // 将时间戳字符串转换为Date对象
        Date date;
        try {
            long timestamp = Long.parseLong(clockTime);
            date = new Date(timestamp);
        } catch (NumberFormatException e) {
            throw new RuntimeException("无效的时间格式");
        }

        // 查询当天的打卡记录
        Clock todayClock = queryTodayClock(user.getId(), new Date());

        // 判断打卡时间是否小于6点
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int hour = cal.get(Calendar.HOUR_OF_DAY);

        int rows;
        if (todayClock == null) {
            // 如果没有找到上班打卡记录，创建新记录
            Clock clock = new Clock();
            clock.setUserId(user.getId());
            clock.setClockOutTime(date);
            clock.setCreateTime(new Date());
            clock.setClockInStatus((byte) 1); // 标记为异常状态（无上班打卡）
            
            // 设置下班打卡状态
            if (hour < 6) {
                clock.setClockOutStatus((byte) 1); // 异常时间下班
            } else {
                clock.setClockOutStatus((byte) 0); // 正常时间下班
            }
            
            rows = clockMapper.insert(clock);
        } else {
            if(todayClock.getClockOutTime() != null){
                return 1;
            }
            // 更新下班时间
            todayClock.setClockOutTime(date);
            
            // 设置下班打卡状态
            if (hour < 6) {
                todayClock.setClockOutStatus((byte) 1); // 异常时间下班
            } else {
                todayClock.setClockOutStatus((byte) 0); // 正常时间下班
            }
            
            rows = clockMapper.updateByPrimaryKey(todayClock);
        }

        return rows;
    }




}
